<?php
/**
 * Created by PhpStorm.
 * User: zhangligang
 * Date: 17/4/27
 * Time: 下午10:55
 */

namespace App\Http\Presenter;


use App\Http\Models\Product;
use Illuminate\Database\Eloquent\Collection;

class ProductPresenter implements Presenter
{

    /**
     *
     */
    public function __construct() {
        //
    }

    /**
     * @param Collection $productList
     * @return array
     */
    public function formatProductList(Collection $productList)
    {

        $result = [];

        foreach ($productList as $product) {

            $result[] = $this->formatProduct($product);
        }

        return $result;
    }

    /**
     * @param Product $product
     * @return array
     */
    public function formatProduct(Product $product)
    {

        if (!$product) return [];

        $saleNum = 0;

        foreach ($product->goods as $goods) {

            $saleNum += $goods->sale_num;
        }

        return [
            'id' => (int)$product->id,
            'title' => $product->title,
            'short' => $product->short,
            'poster' => FormatPresenter::formatImgUrl($product->poster, '40*40'),
            'price' => $product->goods[0]->price,
            'sale_num' => $saleNum
        ];
    }

}